package com.backend.demo1.services;

import com.backend.demo1.config.ApiException;
import com.backend.demo1.mapper.ArticleMapper;
import com.backend.demo1.models.Article;
import com.backend.demo1.utils.RedisUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ArticleMapper articleMapper;

    // 创建新公告的服务逻辑
    public Article createArticle(Article article) {
        try {
            articleMapper.insertArticle(article);
            return article; // 返回插入后的公告对象
        } catch (Exception e) {
            throw new ApiException(500, "创建公告失败: " + e.getMessage());
        }
    }

    // 获取公告列表的服务逻辑
    public List<Article> getArticle() {
        try {
            return articleMapper.findAllArticles();
        } catch (Exception e) {
            throw new ApiException(500, "获取公告列表失败: " + e.getMessage());
        }
    }

    // 根据ID获取公告的服务逻辑
    public Article getArticleByID(String id) {
        try {
            Article article = articleMapper.findArticleById(id);
            if (article == null) {
                throw new ApiException(404, "公告不存在");
            }
            return article;
        } catch (Exception e) {
            throw new ApiException(500, "获取公告失败: " + e.getMessage());
        }
    }

    // 删除公告的服务逻辑
    public void deleteArticleByID(String id) {
        try {
            articleMapper.deleteArticleById(id);
        } catch (Exception e) {
            throw new ApiException(500, "删除公告失败: " + e.getMessage());
        }
    }
    
    
    // 更新公告的服务逻辑
    public void updateArticle(String id, Article inputArticle) {
        try {
            articleMapper.updateArticle(id, inputArticle);
        } catch (Exception e) {
            throw new ApiException(500, "更新公告失败: " + e.getMessage());
        }
    }



    // 点赞公告
    public void likeArticle(String id) {
        try {
            Article article = articleMapper.findArticleById(id.toString());
            if (article == null) {
                throw new ApiException(404, "公告不存在");
            }
            redisUtils.incrementLike(id);
        } catch (Exception e) {
            throw new ApiException(500, "点赞失败: " + e.getMessage());
        }
    }

    // 获取公告点赞数
    public int getLikeArticle(String id) {
        try {
            Article article = articleMapper.findArticleById(id.toString());
            if (article == null) {
                throw new ApiException(404, "公告不存在");
            }
            return redisUtils.getLikeCount(id);// 返回点赞数
        } catch (Exception e) {
            throw new ApiException(500, "获取点赞数失败: " + e.getMessage());
        }
    }
}